package chuangyi.com.org.DOMIHome.Fragments;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.databinding.tool.util.StringUtils;
import android.graphics.Point;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

//import com.yzp.video.activity.MainActivity;
import com.google.android.exoplayer2.DefaultLoadControl;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.LoadControl;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.decoder.DecoderCounters;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.extractor.ExtractorsFactory;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.trackselection.AdaptiveVideoTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelection;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.ui.SimpleExoPlayerView;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
import com.google.android.exoplayer2.video.VideoRendererEventListener;
import com.yzp.video.view.pdf.PDFView;
import com.yzp.video.view.pdf.listener.OnLoadCompleteListener;
import com.yzp.video.view.pdf.listener.OnPageChangeListener;
import com.yzp.video.view.video.MyVideoView;

import java.io.File;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.UUID;

import chuangyi.com.org.DOMIHome.DBManager;
import chuangyi.com.org.DOMIHome.LoadingDialog;
import chuangyi.com.org.DOMIHome.R;
import chuangyi.com.org.DOMIHome.Utils.OSSUtil;
//import chuangyi.com.org.DOMIHome.VideoPlayer;
import chuangyi.com.org.DOMIHome.Utils.Utils;
import chuangyi.com.org.ViewModel.ContextObservable;
import chuangyi.com.org.ViewModel.NetFileCahe;
import chuangyi.com.org.ViewModel.VideoDetail;
import de.hdodenhof.CircleImageView;

/**
 * Created by zxh on 16/12/23.
 */

public class VideoFragment extends CommonFragment implements View.OnClickListener
        , SeekBar.OnSeekBarChangeListener, MediaPlayer.OnInfoListener, MediaPlayer.OnPreparedListener,
        MediaPlayer.OnBufferingUpdateListener {

    private static final int STATUS_NORMAL = 0;
    private static final int STATUS_PLAYING = 1;
    private static final int STATUS_PAUSED = 2;
    private static final int STATUS_STOPED = 3;

    private int videoStatus;

    //视频地址
    private String URI = "";
    //private String URI = "http://2449.vod.myqcloud.com/2449_22ca37a6ea9011e5acaaf51d105342e3.f20.mp4";
    // 屏幕状态  0 横屏  1  竖屏
    private int screenStatus = 0;

    private VideoDetail detail;
    //
//    private MyVideoView videoView;

    private SimpleExoPlayerView videoView;
    private SimpleExoPlayer player;

    private RelativeLayout container;

    private File pdfFile;

    private boolean isConfirming;
    //显示视频时间
    private TextView tv_start;
    private TextView tv_end;
    private ImageView tv_switch;
    private ImageView cover;
    private ImageView pdfCover;
    private ProgressBar pb_view;
    private CircleImageView btn_start;

    private SeekBar sb_view;
    private boolean isTracking = false;
    //
    private Handler mHandler;
    private VideoFragment.ProgressRunnable progressRunnable;
    private VideoFragment.ControllerRunnable controllerRunnable;


    private int savedPos;
    //controller 显示控制
    private RelativeLayout rl_click;
    private RelativeLayout rl_controller;
    //controller 多长时间隐藏
    private long controller_duration = 10000;

    //view 尺寸
//    private int height = 500;
    private int pdf_with = 300;
    private int pdf_height = 200;

    //pdf
    private PDFView pdf_view;
    private ViewGroup.LayoutParams originLayoutParams;
//    private String pdfName = "paper.pdf";

    public interface StartPlayCallback {
        /**
         * 返回是否取消
         *
         * @return
         */
        boolean allowPlay();
    }

    private StartPlayCallback playCallback;

    private boolean isCheckPDF = false;

    public void setPlayCallback(StartPlayCallback playCallback) {
        this.playCallback = playCallback;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mHandler = new Handler();
        progressRunnable = new ProgressRunnable();
        controllerRunnable = new ControllerRunnable();
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onDetach() {
        mHandler.removeCallbacks(progressRunnable);
        if (screenStatus == 1) {
            exitFullscreen();
        }
        if (player != null) {
            player.release();
            player = null;
        }
        super.onDetach();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onPause() {
//        savedPos = videoView.getCurrentPosition();
        if (videoStatus == STATUS_PLAYING) {
            pauseVideo();
        }
        super.onPause();
    }

    @Override
    public void onResume() {
        if (videoStatus == STATUS_PAUSED && savedPos != 0) {
//            player.seekTo(savedPos);
//            videoView.seekTo(savedPos);
        }
        super.onResume();
    }

    @Override
    protected void initView(View view) {
        initVideoAndPdfView(view);
//        videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
//
//            @Override
//            public boolean onError(MediaPlayer mp, int what, int extra) {
//                Log.i("通知", "播放中出现错误");
//
//                switch (what) {
//                    case -1004:
//                        Log.d("Streaming Media", "MEDIA_ERROR_IO");
//                        break;
//                    case -1007:
//                        Log.d("Streaming Media", "MEDIA_ERROR_MALFORMED");
//                        break;
//                    case 200:
//                        Log.d("Streaming Media", "MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK");
//                        break;
//                    case 100:
//                        Log.d("Streaming Media", "MEDIA_ERROR_SERVER_DIED");
//                        break;
//                    case -110:
//                        Log.d("Streaming Media", "MEDIA_ERROR_TIMED_OUT");
//                        break;
//                    case 1:
//                        Log.d("Streaming Media", "MEDIA_ERROR_UNKNOWN");
//                        break;
//                    case -1010:
//                        Log.d("Streaming Media", "MEDIA_ERROR_UNSUPPORTED");
//                        break;
//                }
//                switch (extra) {
//                    case 800:
//                        Log.d("Streaming Media", "MEDIA_INFO_BAD_INTERLEAVING");
//                        break;
//                    case 702:
//                        Log.d("Streaming Media", "MEDIA_INFO_BUFFERING_END");
//                        break;
//                    case 701:
//                        Log.d("Streaming Media", "MEDIA_INFO_METADATA_UPDATE");
//                        break;
//                    case 802:
//                        Log.d("Streaming Media", "MEDIA_INFO_METADATA_UPDATE");
//                        break;
//                    case 801:
//                        Log.d("Streaming Media", "MEDIA_INFO_NOT_SEEKABLE");
//                        break;
//                    case 1:
//                        Log.d("Streaming Media", "MEDIA_INFO_UNKNOWN");
//                        break;
//                    case 3:
//                        Log.d("Streaming Media", "MEDIA_INFO_VIDEO_RENDERING_START");
//                        break;
//                    case 700:
//                        Log.d("Streaming Media", "MEDIA_INFO_VIDEO_TRACK_LAGGING");
//                        break;
//                    case -1004:
//                        videoView.setVideoURI(Uri.parse(URI));
//                        videoView.seekTo(savedPos);
//                        resume();
//                        return true;
//                }
//
//                return false;
//            }
//        });
//        videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
//            @Override
//            public boolean onError(MediaPlayer mp, int what, int extra) {
//                return true;
//            }
//        });
        super.initView(view);
    }

    @Override
    public void setDataModel(ContextObservable dataModel) {
        super.setDataModel(dataModel);
        if (dataModel != null) {
            if (dataModel instanceof VideoDetail) {
                detail = (VideoDetail) dataModel;
                URI = detail.getVideo().getVideopath();
                downloadPdf(detail);
            }
        }
    }

    public void stopPlay() {
        if (videoStatus == STATUS_PAUSED || videoStatus == STATUS_PLAYING) {
        }
    }

    public boolean backPressed() {
        if (screenStatus == 1) {
            exitFullscreen();
            return true;
        }
        return false;
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    private void initVideoAndPdfView(View view) {
        container = (RelativeLayout) view.findViewById(R.id.activity_main);
        cover = (ImageView) view.findViewById(R.id.cover);
        pdfCover = (ImageView) view.findViewById(R.id.pdfCover);
        btn_start = (CircleImageView) view.findViewById(R.id.btn_start);
        btn_start.setOnClickListener(this);
        rl_click = (RelativeLayout) view.findViewById(R.id.rl_click);
        rl_click.setOnClickListener(this);
        rl_controller = (RelativeLayout) view.findViewById(R.id.rl_controller);
        sb_view = (SeekBar) view.findViewById(R.id.sb_view);
        sb_view.setOnSeekBarChangeListener(this);
        tv_start = (TextView) view.findViewById(R.id.tv_start);
        tv_end = (TextView) view.findViewById(R.id.tv_end);
        tv_switch = (ImageView) view.findViewById(R.id.tv_switch);
        tv_switch.setOnClickListener(this);
        pb_view = (ProgressBar) view.findViewById(R.id.pb_view);

        //video
        videoView = (SimpleExoPlayerView) view.findViewById(R.id.vv_view);
        videoView.setUseController(false);
        prepareVideoView(getActivity());
//        videoView = (MyVideoView) view.findViewById(R.id.vv_view);
//        videoView.setOnInfoListener(this);
//        videoView.setOnPreparedListener(this);

        //设置view 尺寸
        videoView.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.MATCH_PARENT));
        rl_controller.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));

        mHandler.post(progressRunnable);
        mHandler.postDelayed(controllerRunnable, controller_duration);

        //pdf
        pdf_view = (PDFView) view.findViewById(R.id.pdf_view);
        pdf_view.setOnClickListener(this);
        //PDF 显示
//        pdf_view.fromAsset(pdfName).defaultPage(1).showMinimap(false)
//                .enableSwipe(true).onLoad(new OnLoadCompleteListener() {
//            @Override
//            public void loadComplete(int nbPages) {
////                Toast.makeText(MainActivity.this, "loadComplete",
////                        Toast.LENGTH_SHORT).show();
//            }
//        }).onPageChange(new OnPageChangeListener() {
//            @Override
//            public void onPageChanged(int page, int pageCount) {
////                setTitle(format("%s %s / %s", pdfName, page, pageCount));
//            }
//        }).load();
//        File file = new File(Environment.getExternalStorageDirectory()
//                + "/test/11.pdf");
//        pdf_view.fromFile(file).defaultPage(1).showMinimap(false)
//                .enableSwipe(true).onLoad(new OnLoadCompleteListener() {
//            @Override
//            public void loadComplete(int nbPages) {
//                Toast.makeText(MainActivity.this, "loadComplete",
//                        Toast.LENGTH_SHORT).show();
//            }
//        }).onPageChange(new OnPageChangeListener() {
//            @Override
//            public void onPageChanged(int page, int pageCount) {
//                setTitle(format("%s %s / %s", pdfName, page, pageCount));
//            }
//        }).load();
    }

    private void downloadPdf(final VideoDetail detail) {
        if (!Utils.isNullOrEmpty(detail.getNotespath())) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    NetFileCahe cache = DBManager.getInstance(detail.getContext())
                            .getDownloadedFile(detail.getNotespath());
                    if (!confirmDownloadedFile(cache, detail.getContext())) {
                        try {
                            downloadPdf((Activity) detail.getContext(), detail.getNotespath());
                        } catch (Exception ex) {
                            detail.showToast("读取课件时发生错误");
                        }
                    } else {
                        displayPdf();
                    }
                }
            }).start();
        }
    }

    private boolean confirmDownloadedFile(NetFileCahe cache, Context context) {
        File file = null;
        pdfFile = null;
        if (cache != null) {
            if (Utils.isNullOrEmpty(cache.getPath())) {
                DBManager.getInstance(context).deleteDownloadedFile(cache);
                return false;
            }
            file = new File(cache.getPath());
            if (file.exists()) {
                pdfFile = file;
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    private void downloadPdf(final Activity activity, final String url) {
        File file = activity.getExternalCacheDir();
        if (!file.exists()) {
            file.mkdir();
        }
        UUID uuid = UUID.randomUUID();
        final File downloadFile = new File(String.format("%s/%s.pdf", file.getPath(), uuid.toString()));
        if (OSSUtil.downloadFile(activity.getApplicationContext(), url, downloadFile)) {
            DBManager.getInstance(activity).insertDownloadedFile(url, downloadFile.getAbsolutePath());
            if (downloadFile.exists()) {
                // 显示PDF
                pdfFile = downloadFile;
                displayPdf();
            }
        }

    }

    /**
     * 更新界面
     */
    class ProgressRunnable implements Runnable {
        @Override
        public void run() {
//            if (videoView.isPlaying()) {
            if (videoStatus == STATUS_PLAYING) {
                //时间转换格式
                SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");
                //
//                tv_start.setText(formatter.format(videoView.getCurrentPosition()) + "");
//                tv_end.setText(formatter.format(videoView.getDuration()) + "");
//                sb_view.setMax(Integer.valueOf(videoView.getDuration()));
//                sb_view.setProgress(Integer.valueOf(videoView.getCurrentPosition()));
                tv_start.setText(formatter.format(player.getCurrentPosition()) + "");
                tv_end.setText(formatter.format(player.getDuration()) + "");
                sb_view.setMax((int) player.getDuration());
                sb_view.setProgress((int) player.getCurrentPosition());
                //播放按钮状态
                btn_start.setBackgroundResource(R.drawable.click_pause_selector);
            } else {
                //播放按钮状态
                btn_start.setBackgroundResource(R.drawable.click_play_selector);
            }
            mHandler.postDelayed(this, 1000);
        }
    }

    /**
     * controller 显示  隐藏
     */
    class ControllerRunnable implements Runnable {
        @Override
        public void run() {
            rl_controller.setVisibility(View.GONE);
            mHandler.removeCallbacks(this);
        }
    }

    public void displayPdf() {
        Activity activity = getActivity();
        if (activity != null && videoStatus == STATUS_PLAYING) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        pdf_view.fromFile(pdfFile).defaultPage(1).showMinimap(false)
                                .enableSwipe(true).onLoad(new OnLoadCompleteListener() {
                            @Override
                            public void loadComplete(int nbPages) {
//                Toast.makeText(MainActivity.this, "loadComplete",
//                        Toast.LENGTH_SHORT).show();
                            }
                        }).onPageChange(new OnPageChangeListener() {
                            @Override
                            public void onPageChanged(int page, int pageCount) {
//                setTitle(format("%s %s / %s", pdfName, page, pageCount));
                            }
                        }).load();
                    } catch (Exception ex) {

                    }
                }
            });
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (isTracking) {
            player.seekTo(progress);
//            videoView.seekTo(progress);
        }
//        savedPos = videoView.getCurrentPosition();
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        isTracking = true;
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        isTracking = false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.pdf_view:
                if (!rl_controller.isShown()) {
                    switchControllerBar();
                    return;
                }
                if (!isCheckPDF) {
                    isCheckPDF = true;
//                    pdfCover.setVisibility(View.GONE);
                    pdfCover.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, videoView.getHeight()));
                    pdf_view.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, videoView.getHeight()));
                } else {
                    isCheckPDF = false;
                    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(pdf_with, pdf_height);
                    params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
                    pdf_view.setLayoutParams(params);
                    pdfCover.setLayoutParams(params);
                }
                break;
            case R.id.rl_click:
                switchControllerBar();
                break;
            case R.id.tv_switch:
                if (screenStatus == 0) {
                    intoFullscreen();
                } else if (screenStatus == 1) {
                    exitFullscreen();
                }
                break;
            case R.id.btn_start:
//                if (videoView.isPlaying()) {
                if (videoStatus == STATUS_PLAYING) {
                    pauseVideo();
                } else {
                    if (videoStatus == STATUS_PAUSED) {
                        resume();
                        return;
                    }
                    if (URI == null || "".equals(URI)) {
                        videoStatus = STATUS_STOPED;
                        Toast.makeText(getActivity(), "无效视频", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    Uri uri = null;
                    try {
                        uri = Uri.parse(URI);
                    } catch (Exception ex) {
                        videoStatus = STATUS_STOPED;
                        Toast.makeText(getActivity(), "无效的视频路径", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    playVideo();
                }
                break;
        }
    }

    protected void switchControllerBar() {
        if (rl_controller.isShown()) {
            rl_controller.setVisibility(View.GONE);
        } else {
            rl_controller.setVisibility(View.VISIBLE);
            mHandler.postDelayed(controllerRunnable, controller_duration);
        }
    }

    private void intoFullscreen() {
        if (detail != null) {
            detail.getVideo().setOtherVisibility(View.GONE);
        }
        WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
        Point size = new Point();
        wm.getDefaultDisplay().getSize(size);
        tv_switch.setBackgroundResource(R.mipmap.skin_shrink_video);
        screenStatus = 1;
        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(size.y, size.x);
        originLayoutParams = container.getLayoutParams();
        videoView.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT));
        container.setLayoutParams(layoutParams);
        container.setGravity(Gravity.CENTER_HORIZONTAL);

        rl_controller.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));

        if (isCheckPDF) {
            pdfCover.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, size.x));
            pdf_view.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, size.x));
        }
    }

    private void exitFullscreen() {
        if (detail != null) {
            detail.getVideo().setOtherVisibility(View.VISIBLE);
        }
        tv_switch.setBackgroundResource(R.mipmap.skin_enlarge_video);
        screenStatus = 0;
        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        container.setLayoutParams(originLayoutParams);
        container.setGravity(Gravity.NO_GRAVITY);
        rl_controller.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
    }

    public void pauseVideo() {
        player.setPlayWhenReady(false);
//        videoView.pause();
//        cover.setImageResource(R.mipmap.pause_screen);
//        cover.setVisibility(View.VISIBLE);
        btn_start.setBackgroundResource(R.drawable.click_play_selector);
        videoStatus = STATUS_PAUSED;
    }

    public void playVideo() {
        if (isConfirming) {
            Toast.makeText(getActivity(), "正在确认视频播放权限，请稍候", Toast.LENGTH_SHORT).show();
            return;
        }
        isConfirming = true;
        videoStatus = STATUS_PLAYING;
        btn_start.setBackgroundResource(R.drawable.click_pause_selector);
        new Thread(new Runnable() {
            @Override
            public void run() {
                Activity activity = getActivity();
                if (isDetached() || activity == null) {
                    Log.i("VideoFragment", "Fragement Detached");
                    return;
                }
                if (playCallback != null) {

                    if (!playCallback.allowPlay()) {
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                videoStatus = STATUS_STOPED;
                                btn_start.setBackgroundResource(R.drawable.click_play_selector);
                            }
                        });
                        isConfirming = false;
                        return;
                    }
                }
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        displayPdf();
                        cover.setVisibility(View.GONE);
                        pdfCover.setVisibility(View.GONE);
                        setVideoSource(Uri.parse(URI));
                        player.setPlayWhenReady(true);
//                        videoView.setVideoURI(Uri.parse(URI));
//                        videoView.start();
                    }
                });
                isConfirming = false;
            }
        }).start();
    }

    public void resume() {
//        cover.setVisibility(View.GONE);
        btn_start.setBackgroundResource(R.drawable.click_pause_selector);
        videoStatus = STATUS_PLAYING;
        player.setPlayWhenReady(true);
//        videoView.start();
    }

    public void hideVideoView() {
        if (rl_click != null) {
            rl_click.setVisibility(View.GONE);
//            cover.setVisibility(View.VISIBLE);
//            videoView.setVisibility(View.GONE);
            player.setPlayWhenReady(false);
            videoView.getVideoSurfaceView().setVisibility(View.GONE);
            if (videoStatus == STATUS_PLAYING) {
                videoStatus = STATUS_PAUSED;
            }
        }
    }

    public void showVideoView() {
        if (rl_click != null) {
            SurfaceView view = (SurfaceView)videoView.getVideoSurfaceView();
            view.setVisibility(View.VISIBLE);
            player.setVideoSurfaceView(view);
            rl_click.setVisibility(View.VISIBLE);
            if(URI != null && !"".equals(URI)){
                setVideoSource(Uri.parse(URI));
            }
        }
    }

    @Override
    public boolean onInfo(MediaPlayer mp, int what, int extra) {
        switch (what) {
            case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                pb_view.setVisibility(View.VISIBLE);
                btn_start.setVisibility(View.GONE);
                mHandler.removeCallbacks(controllerRunnable);
                break;
            case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                if (mp.isPlaying()) {
                    pb_view.setVisibility(View.GONE);
                    btn_start.setVisibility(View.VISIBLE);
                    mHandler.postDelayed(controllerRunnable, controller_duration);
                }
                break;
        }
        return true;
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {

    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        pb_view.setVisibility(View.GONE);
        btn_start.setVisibility(View.VISIBLE);
    }

    private void setVideoSource(Uri uri) {
        // Measures bandwidth during playback. Can be null if not required.
        DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
        // Produces DataSource instances through which media data is loaded.
        DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(getActivity(),
                Util.getUserAgent(getActivity(), "DOMIHome"), bandwidthMeter);
        // Produces Extractor instances for parsing the media data.
        ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
        // This is the MediaSource representing the media to be played.
        MediaSource videoSource = new ExtractorMediaSource(uri, dataSourceFactory, extractorsFactory, null, null);
        // Prepare the player with the source.
        player.prepare(videoSource, false, false);
    }

    private void prepareVideoView(Context context) {
//        Handler mainHandler = new Handler();
        BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
        TrackSelection.Factory videoTrackSelectionFactory =
                new AdaptiveVideoTrackSelection.Factory(bandwidthMeter);
        TrackSelector trackSelector =
                new DefaultTrackSelector(videoTrackSelectionFactory);

// 2. Create a default LoadControl
        DefaultLoadControl loadControl = new DefaultLoadControl();

// 3. Create the player
        player = ExoPlayerFactory.newSimpleInstance(context, trackSelector, loadControl);
        videoView.setPlayer(player);
        videoView.setKeepScreenOn(true);
    }
}
